//index.js

const utils = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    today: '',
    inputCity: '',
    city: '',
    district: '',
    street: '',
    weather: {},

    viewShowed: false,
    catList: [],
    list1: ['北京', '成都', '南京', '重庆', '哈尔滨', '武汉', '石家庄', '长春', '南昌','宜宾','佛山','深圳']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      today: utils.formatTime(new Date()).split(' ')[0],
      city:options.city
    });
    this.getWeather(this.data.city)
  },

  getWeather: function(city) {
    const that = this;
    wx.request({
      url: 'https://wthrcdn.etouch.cn/weather_mini?city=' + city,
      data: {},
      success: function(res) {
        if (res.data.status === 1002) {
          wx.showModal({
            title: '提示',
            content: '输入的城市名称有误，请重新输入！',
            showCancel: false,
            success: function(res) {
              that.setData({
                inputCity: ""
              })
            }
          })
        } else {
          const weatherObj = res.data.data;
          for (var i = 0; i < weatherObj.forecast.length; i++) {
            var d = weatherObj.forecast[i].date;
            var dfl = weatherObj.forecast[i].fengli;
            //<a日星期b> -> <a日 星期b>
            weatherObj.forecast[i].data = ' ' + d.replace('星期', ' 星期');
            //<![CDATA[x]]> -> <x>
            weatherObj.forecast[i].fengli = dfl.replace('<![CDATA[', '').replace(']]>', '');
          }
          that.setData({
            weather: weatherObj,
            inputCity: ''
          })

        }
      }
    })
  },

  linconfirm: function(e) {
    this.setData({
      inputCity: e.detail.value,
      city: e.detail.value
    })
    this.getWeather(this.data.inputCity)
  },

  hideInput: function() {
    this.setData({
      inputCity: "",
      viewShowed: false,
    });
  },

  linchange: function(e) {
    var value = e.detail.value
    var that = this;
    var list1 = that.data.list1
    if (value == '') {
      that.setData({
        viewShowed: false,
      });
    } else {
      if (e.detail.cursor) {
        var arr = [];
        for (var i = 0; i < list1.length; i++) {
          if (list1[i].indexOf(value) >= 0) {
            arr.push(list1[i]);
          }
        }
        that.setData({
          viewShowed: true,
          carList: arr
        });
      }
    }
  },

  search:function (res) {
    var index = res.currentTarget.dataset.index
    var that = this;
    that.setData({
      inputCity: that.data.carList[index],
      city: that.data.carList[index],
      viewShowed: false,
    })
    this.getWeather(this.data.inputCity)
  }

})